package com.gitee.cui.client.client;

import com.gitee.cui.common.common.bean.User;
import com.gitee.cui.common.common.bean.msg.ProtoMsg;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 客户端session信息
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/27 14:58
 **/
@Data
@Slf4j
public class ClientSession {

    public static final AttributeKey<ClientSession> SESSION_KEY = AttributeKey.valueOf("SESSION_KEY");

    public ClientSession (Channel channel) {
        this.channel = channel;
        this.sessionId = String.valueOf(-1);
        channel.attr(SESSION_KEY).set(this);
    }

    /**
     * 用户实现客户端会话管理的核心
     */
    private Channel channel;

    /**
     * 用户信息
     */
    private User user;

    /**
     * 保存登录后的服务端sessionId
     */
    private String sessionId;

    private boolean connected = false;

    private boolean login = false;

    /**
     * session中村的胡德session变量属性值
     */
    private Map<String, Object> map = new HashMap<>();

    /**
     * 登录成功
     * @param ctx 通道处理器上下文
     * @param message 登录返回信息
     */
    public static void loginSuccess(ChannelHandlerContext ctx, ProtoMsg.Message message) {
        Channel channel = ctx.channel();
        ClientSession session = channel.attr(SESSION_KEY).get();
        session.setSessionId(message.getSessionId());
        session.setLogin(true);
        log.info("登录成功！");
    }

    /**
     * 从通道中获取用户session
     * @param ctx 通道处理器上下文
     * @return session信息
     */
    public static ClientSession getSession(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        ClientSession session = channel.attr(SESSION_KEY).get();
        return session;
    }

    /**
     * 关闭通道
     */
    public void close() {
        connected = false;

        ChannelFuture future = channel.close();
        future.addListener(close -> {
            if (close.isSuccess()) {
                log.error("连接顺利断开");
            }
        });
    }
}
